package cake.web.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cake.dao.CakeDao;
import cake.dao.CakeImgDao;
import cake.dao.CommentDao;
import cake.dao.impl.CakeDaoImpl;
import cake.dao.impl.CakeImgDaoImpl;
import cake.dao.impl.CommentDaoImpl;
import cake.entity.Cake;
import cake.entity.CakeImg;
import cake.entity.Comment;

@WebServlet("/details.html")
public class DetailsServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		CommentDao commentDao = new CommentDaoImpl();
		int id = Integer.parseInt(req.getParameter("kid"));
		CakeDao cakeDao = new CakeDaoImpl();
		Cake cake = cakeDao.getCakeById(id);
		req.setAttribute("cake", cake);
		
		final int pageSize = 3;
		int rows = commentDao.fetchCommentRows(id);
    	int totalPages = rows%pageSize==0?(rows/pageSize):(rows/pageSize+1);
    	req.setAttribute("totalPages", totalPages);
    	int pageNum = 1;
    	if(req.getParameter("page")!=null){
    		pageNum = Integer.parseInt(req.getParameter("page"));
    	}
    	req.setAttribute("pageNum", pageNum);
		List<Comment> comments = commentDao.getThreeAndUser(id,pageSize,pageNum);
		req.setAttribute("comments", comments);
		
		CakeImgDao cakeImgDao = new CakeImgDaoImpl();
		List<CakeImg> cakeImgs = cakeImgDao.getImgByCid(id);
		for(CakeImg c:cakeImgs) {
			System.out.println(c.getImg());
		}
		req.setAttribute("cakeImgs", cakeImgs);
		
		req.getRequestDispatcher("details.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		int uid = Integer.parseInt(req.getParameter("uid"));
		int cid = Integer.parseInt(req.getParameter("cid"));
		int score = Integer.parseInt(req.getParameter("score"));
		String content = req.getParameter("content");
		CommentDao commentDao = new CommentDaoImpl();
		Date date = new Date();
		java.sql.Date dateS = new java.sql.Date(date.getTime());
		Comment c = new Comment(0,uid,cid,score,content,dateS);
		commentDao.addComment(c);
		resp.sendRedirect("details.html?kid=1");
	}
	
	
	
}
